﻿using System;
using System.Globalization;
using System.Reflection;
using System.Windows.Forms;
using HgCo.WindowsLive.SkyDrive.TotalCommander.Plugins.Support;

namespace HgCo.WindowsLive.SkyDrive.TotalCommander.Plugins.Forms
{
    /// <summary>
    /// Represents a dialog window for connection to SkyDrive.
    /// </summary>
    internal partial class SkyDriveWfxLogOnForm : Form
    {
        /// <summary>
        /// Gets or sets the session.
        /// </summary>
        /// <value>The session.</value>
        public SkyDriveSession Session { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SkyDriveWfxLogOnForm"/> class.
        /// </summary>
        internal SkyDriveWfxLogOnForm()
            : base()
        {
            InitializeComponent();

            var assemblyName = new AssemblyName(Assembly.GetExecutingAssembly().FullName);
            this.Text = String.Format(
                CultureInfo.InvariantCulture,
                "SkyDrive Explorer {0}.{1}.{2} - Login",
                assemblyName.Version.Major,
                assemblyName.Version.Minor,
                assemblyName.Version.Build);
            this.Icon = Resources.SkyDriveWfx.mini_storage;

            var config = SkyDriveWfxConfiguration.Load();

            txtUserName.Text = config.UserName;
            txtUserPassword.Text = SkyDriveWfxCryptoEngine.Decrypt(config.UserPassword);
            txtCid.Text = config.Cid;

            var connectionType = config.ConnectionType;
            rbtnAccessPrivate.Checked = connectionType == SkyDriveWfxConnectionType.Private;
            rbtnAccessPublic.Checked = connectionType == SkyDriveWfxConnectionType.Public;
        }

        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// Handles the Click event of the btnConnect control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                Enabled = false;
                UseWaitCursor = true;

                if (rbtnAccessPrivate.Checked)
                {
                    var srvSkyDrive = new SkyDriveServiceClient();
                    srvSkyDrive.Timeout = SkyDriveWfx.SkyDriveServiceClientTimeout;
                    srvSkyDrive.LogOn(txtUserName.Text, txtUserPassword.Text);
                    Session = srvSkyDrive.Session;
                }
                else 
                {
                    if (txtCid.Text.StartsWith("cid-", StringComparison.InvariantCultureIgnoreCase))
                        txtCid.Text = txtCid.Text.Remove(0, "cid-".Length);
                    var session = new SkyDriveSession { Cid = txtCid.Text };
                    var srvSkyDrive = new SkyDriveServiceClient(session);
                    srvSkyDrive.ListRootWebFolderItems();
                    Session = srvSkyDrive.Session;
                }

                var config = SkyDriveWfxConfiguration.Load();
                config.UserName = txtUserName.Text;
                config.UserPassword = SkyDriveWfxCryptoEngine.Encrypt(txtUserPassword.Text);
                config.Cid = txtCid.Text;
                config.ConnectionType = 
                    rbtnAccessPrivate.Checked ? SkyDriveWfxConnectionType.Private :
                    rbtnAccessPublic.Checked ? SkyDriveWfxConnectionType.Public : SkyDriveWfxConnectionType.None;
                config.Save();

                DialogResult = DialogResult.OK;
            }
            catch
            {
                MessageBox.Show("Failed to connect/log on to SkyDrive!");
                DialogResult = DialogResult.None;
            }
            finally
            {
                Enabled = true;
                UseWaitCursor = false;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnDonate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnDonate_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6021108");
        }

        /// <summary>
        /// Handles the CheckedChanged event of the rbtnContent control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void rbtnContent_CheckedChanged(object sender, EventArgs e)
        {
            gboxAccountPrivate.Enabled = rbtnAccessPrivate.Checked;
            gboxAccountPublic.Enabled = rbtnAccessPublic.Checked;

            btnConnect.Enabled = rbtnAccessPrivate.Checked || rbtnAccessPublic.Checked;
        }
    }
}
